# Create your views here.
import os

import xlrd
from rest_framework.response import Response
from rest_framework.views import APIView
from Seats.models import Team
from Seats.packaging import seats_tatus_save
from Seats.tests import readExcelDataByName, getColumnIndex
from utils.page_like import efficient_pager
import datetime

# 创建班组
class Team_View(APIView):
    def get(self, request):
        page = request.GET.get('page', '')
        page_size = request.GET.get('page_size', '')
        account_id = request.GET.get('account_id', '')
        print(account_id)
        if not account_id:
            return Response({"code": 403, "msg": "企业表示为必须参数"})
        status = request.GET.get('status', '')
        if status == '0':
            sql = "select count(id) from zb_team where account_id=%s and status='0'" % account_id
            count = efficient_pager(count='count', sql=sql)
            sql = "select * from zb_team where account_id='%s' and status='0'" % account_id
            data_list = efficient_pager(sql=sql, page=page, page_size=page_size)
            if type(data_list) is str:
                return Response({"code": 500, "msg": "系统繁忙", "error": data_list})
            return Response({"code": 200, "msg": "查询成功", "total": count, "data": data_list})
        else:
            sql = "select count(id) from zb_team where account_id=%s and status='1'" % account_id
            count = efficient_pager(count='count', sql=sql)
            sql = "select * from zb_team where account_id='%s' and status='1'" % account_id
            data_list = efficient_pager(sql=sql, page=page, page_size=page_size)
            if type(data_list) is str:
                return Response({"code": 500, "msg": "系统繁忙", "error": data_list})
            return Response({"code": 200, "msg": "查询成功", "total": count, "data": data_list})

    def post(self, request):
        team_name = request.data.get('team_name', '')
        manager = request.data.get('manager', '')
        allocation = request.data.get('allocation', '')
        account_id = request.data.get('account_id', '')
        team = Team.objects.filter(team_name=team_name, account_id=account_id, status=0).first()
        if team:
            return Response({"code": 403, "msg": "班组已存在"})
        try:
            Team(team_name=team_name, manager=manager, allocation=allocation, account_id=account_id).save()
            return Response({"code": 200, "msg": "新建班组成功"})
        except Exception as e:
            return Response({"code": 500, "msg": "系统繁忙", "error": str(e)})

    def put(self, request):
        id = request.data.get('id', '')
        team_name = request.data.get('team_name', '')
        manager = request.data.get('manager', '')
        allocation = request.data.get('allocation', '')
        account_id = request.data.get('account_id', '')
        team = Team.objects.filter(id=id, status=0).first()
        if team_name != team.team_name:
            if Team.objects.filter(team_name=team_name, account_id=account_id, status=0).first():
                return Response({"code": 403, "msg": "班组已存在"})
        if not team:
            return Response({"code": 403, "msg": "班组已被删除或不可用"})
        try:
            team.team_name = team_name
            team.manager = manager
            team.allocation = allocation
            team.account_id = account_id
            team.save()
            return Response({"code": 200, "msg": "修改班组成功"})
        except Exception as e:
            return Response({"code": 500, "msg": "系统繁忙", "error": str(e)})

    def delete(self, request):
        confirm = request.data.get('confirm', '')
        id = request.data.get('id', '')
        try:
            if confirm == '1':
                team = Team.objects.filter(id=id, status='1').first()
                if not team:
                    return Response({"code": 403, "msg": "数据正在使用，无法彻底删除"})
                team.delete()
                return Response({"code": 200, "msg": "已彻底删除"})
            team = Team.objects.filter(id=id, status='0').first()
            if not team:
                return Response({"code": 403, "msg": "数据不存在或已被删除"})
            team.status = '1'
            team.save()
            return Response({"code": 200, "msg": "已删除"})
        except Exception as f:
            return Response({"code": 500, "msg": "系统繁忙", "error": str(f)})

# 坐席分配(创建坐席登录账号)
class Seats_Allocation_View(APIView):
    def get(self, request):
        pass

    def post(self, request):
        pass

    def put(self, request):
        pass

    def delete(self, request):
        pass

# 坐席登录
class Seats_Login_View(APIView):
    def get(self, request):
        pass

    def post(self, request):
        pass

    def put(self, request):
        pass

    def delete(self, request):
        pass

# 坐席状态控制
class Seats_Status_View(APIView):
    def get(self, request):
        pass

    def post(self, request):
        seats_number = request.data.get('seats_number','')
        status = request.data.get('status','')
        free_time = request.data.get('free_time','')
        account_name = request.data.get('free_time','')
        account_tag = request.data.get('account_tag','')
        try:
            seats_tatus_save(seats_number=seats_number,status=status,free_time=free_time,account_name=account_name,account_tag=account_tag)
            return Response({"code":200,"msg":"存储成功"})
        except Exception as e:
            return Response({"code":500,"msg":"系统繁忙","e":str(e)})

    def put(self, request):
        pass

    def delete(self, request):
        pass


class Read_Files_View(APIView):
    def post(self,request):
        t_id = request.data.get('e_id','')
        account_tag = request.data.get('account_tag','')
        execl_files = request.FILES.get('execl_files','')
        batch = request.data.get('batch','')
        # 打开文件
        excel_name = execl_files.name
        a = excel_name.split(".")[0] + datetime.datetime.now().strftime("%Y%m%d%H%M%S") + '.xlsx'
        destination = open(os.path.join("/tmp/wenjian", a), 'wb+')
        for chunk in execl_files.chunks():
            destination.write(chunk)
        destination.close()
        wb = xlrd.open_workbook('/tmp/wenjian/{}'.format(a))
        sheet1 = wb.sheets()[0]
        nrows = sheet1.nrows
        list_xls = sheet1.row_values(0)
        # print(list_xls)
        data_list = {
        "field_b3b091e1": "单行文本",
        "field_9af0226a": "单行文本1",
        "thread_name": "线索名称",
        "thread_source": "数据来源",
        "mobile": "手机",
        "telephone": "电话",
        "email": "邮箱",
        "level": "客户级别",
        "industry": "客户行业",
        "des": "备注"
        }
        table = readExcelDataByName('/tmp/wenjian/' + a, 'Sheet1')
        print(getColumnIndex(table, '线索名称'))
        print(getColumnIndex(table, '数据来源'))
        print(getColumnIndex(table, '手机'))
        print(getColumnIndex(table, '电话'))
        for data in list_xls:
            for k, v in data_list.items():
                if data == v:
                    # print(k,data)
                    pass
        return Response({"code":200})